package org.csu.jpetstore_user.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.jpetstore_user.entity.Account;
import org.csu.jpetstore_user.entity.Cart;
import org.csu.jpetstore_user.entity.CartItem;
import org.csu.jpetstore_user.entity.Item;
import org.csu.jpetstore_user.persistence.ItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Iterator;


@Controller
public class CartController {

    @Autowired
    private ItemMapper itemMapper;

    //购物车页面
    @GetMapping("/cartForm")
    public String cartForm(HttpSession session){
        //显示购物车信息
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart == null){
            cart = new Cart();
        }
        session.setAttribute("cart",cart);
        return "cart/cart";
    }
    //item加入购物车
    @GetMapping("/addItemToCart")
    public String addItemToCart(HttpSession session,@RequestParam("workingItemId") String workingItemId){
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart == null){
            cart = new Cart();
        }
        session.setAttribute("cart",cart);
        Item item = itemMapper.selectById(workingItemId);
        if (cart.containsItemId(workingItemId)) {
            cart.incrementQuantityByItemId(workingItemId);
        } else {
            //TODO 库存问题待解决









            cart.addItem(item, true);
            System.out.println(workingItemId+" 加入购物车......");
        }
        updateCart(session,cart);
        return "cart/cart";
    }

    //从购物车删除Item
    @GetMapping("removeCartItem")
    public String removeCartItem(HttpSession session,@RequestParam("workingItemId") String workingItemId){
        Cart cart = (Cart) session.getAttribute("cart");
        cart.removeItemById(workingItemId);

        System.out.println(workingItemId+" 从购物车移除......");
        updateCart(session,cart);
        return "cart/cart";
    }

    @GetMapping("updateCart")
    public void updateCart(HttpSession session,Cart cart){

        Iterator<CartItem> cartItems = cart.getAllCartItems();
        while (cartItems.hasNext()) {
            CartItem cartItem = cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                int quantity = cartItem.getQuantity();
                cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItems.remove();
                }
            } catch (Exception e) {
                //ignore parse exceptions on purpose
            }
        }
        session.setAttribute("cartItems",cartItems);
    }

}
